import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
} from '@ant-design/pro-components';

export type EditFormProps = {
  title: string;
  open: boolean;
  onOpenChange: React.Dispatch<React.SetStateAction<boolean>>;
  onFinish: (values: API.MenuItem) => Promise<void>;
  values?: Partial<API.MenuItem> & {
    isFixParent: boolean;
    fixParentId: number | undefined;
    valueEnum: { value: number | undefined; label: string }[];
  };
};

const isRoutePath = (rule: any, value: string) => {
  const routeRegex = /^\/[a-zA-Z0-9_-]+(\/[a-zA-Z0-9_-]+)*$/;

  if (!routeRegex.test(value)) {
    return Promise.reject(new Error('请输入正确的路由路径'));
  }

  return Promise.resolve();
};

const isWord = (rule: any, value: string) => {
  const wordRegex = /^[a-zA-Z0-9]+$/;

  if (!wordRegex.test(value)) {
    return Promise.reject(new Error('请输入正确的单词'));
  }

  return Promise.resolve();
};

const EditForm: React.FC<EditFormProps> = (props) => {
  return (
    <ModalForm
      title={props.title}
      open={props.open}
      onOpenChange={props.onOpenChange}
      onFinish={props.onFinish}
      initialValues={props.values}
      modalProps={{ destroyOnClose: true }}
    >
      <ProFormDigit name="id" hidden />
      <ProFormText
        label="路由路径"
        name="path"
        rules={[{ required: true, message: '请填写正确的路由路径', validator: isRoutePath }]}
      />
      <ProFormText
        label="路由名称"
        name="name"
        rules={[
          {
            required: true,
            message: '请填写正确的路由名称，只能是单个英文单词',
            validator: isWord,
          },
        ]}
      />
      <ProFormText
        label="菜单名称"
        name="title"
        rules={[{ required: true, message: '请填写菜单名称' }]}
      />
      <ProFormSelect
        label="父节点"
        name="parentId"
        disabled={props?.values?.isFixParent ? true : false}
        options={props?.values?.valueEnum}
        initialValue={
          props?.values?.parentId ? props?.values?.parentId : props?.values?.fixParentId
        }
      />
      <ProFormSwitch label="是否隐藏" name="hidden" initialValue={false} />
      <ProFormDigit label="排序值" name="sort" initialValue={99} />
    </ModalForm>
  );
};

export default EditForm;
